<?php

namespace app\index\controller;

use app\common\IndexController;
use app\index\model\User as UserModel;
use app\validate\User as UserValidate;
use app\utils\Email;
use think\facade\Cache;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class User extends IndexController
{
    //发送验证码
    public function sendCode()
    {
        $email = input('post.email');
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return error('邮箱格式不正确');
        }

        // 生成验证码
        $code = sprintf("%06d", random_int(0, 999999));

        // 发送邮件
        $emailService = new Email();
        if ($emailService->sendVerificationCode($email, $code)) {
            // 存储验证码和发送时间
            Cache::set('email_code_' . $email, $code, 300);  // 5分钟有效期
            return success('验证码发送成功');  // 成功时返回
        }
        return error('验证码发送失败');  // 失败时返回
    }
    //注册
    public function regist()
    {
        $data = input("post.");

        $validate = new UserValidate();
        try {
            // 验证数据
            if (!$validate->check($data)) {
                return error($validate->getError());
            }
            $cached_code = Cache::get('email_code_' . $data['email']);
            if (!$cached_code) {
                return error('验证码已过期');
            } elseif ($cached_code != $data['code']) {
                return error('验证码错误');
            }
            //检查email是否被注册
            $isUser = UserModel::where("email", $data['email'])->find();
            if (!$isUser) {
                $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
                // 生成 6 位随机数
                $randomNumber = rand(100000, 999999);
                // 组合昵称
                $data['nickname'] = "用户" . $randomNumber;
                $user = new UserModel();
                $res = $user->save($data);
                if ($res) {
                    Cache::delete(('email_code_' . $data['email']));
                    return success('注册成功');
                } else {
                    return error('注册失败');
                }
            } else {
                return error("邮箱已被注册");
            }
        } catch (\Throwable $th) {
            //throw $th;
            return error('系统错误' . $th->getMessage());
        }
    }
    //登录
    public function login()
    {
        $data = input('post.');
        try {
            // 验证登录数据
            $validate = new UserValidate();
            if (!$validate->check($data)) {
                return error($validate->getError());
            }
            // 查找用户
            $user = UserModel::where('email', $data['email'])->find();
            if (!$user) {
                return error('用户不存在，请先注册');
            }

            //验证密码
            if (!password_verify($data['password'], $user['password'])) {
                return error('密码错误');
            }
            //生成token
            $key = 'dkfjkldfjkl';
            $payload = [
                'iss' => 'campus-app',  // 签发者
                'aud' => 'campus-user', // 接收者
                'iat' => time(),        // 签发时间
                'exp' => time() + 7200 * 12, // 过期时间，2小时
                'uid' => $user['id'],   // 用户ID
            ];
            $token = JWT::encode($payload, $key, 'HS256');
            Cache::set('token_' . $user['id'], $token, 7200 * 12);
            return success('登录成功', [
                'token' => $token,
                'user' => [
                    'id' => $user['id'],
                    'email' => $user['email'],
                    'nickname' => $user['nickname'],
                    'avatar' => $user['avatar']
                ]
            ]);
        } catch (\Throwable $th) {
            //throw $th;
            return error('系统错误：' . $th->getMessage());
        }
    }
    //获取用户信息
    public function getUser()
    {
        $id = $this->userid;
        $user = UserModel::where('id', $id)->find();
        return success('获取成功', [
            'id' => $id,
            'email' => $user['email'],
            'avatar' => $user['avatar'],
            'nickname' => $user['nickname'],
            'intro' => $user['intro'],
            'gender' => $user['gender'],
            'location' => $user['location'],
        ]);
    }
}
